package com.ruoyi.record.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.BasicPost;
import com.ruoyi.basic.domain.BasicUser;
import com.ruoyi.basic.mapper.BasicPostMapper;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.record.domain.RecordCompete;
import com.ruoyi.record.domain.RecordCompeteInfo1;
import com.ruoyi.record.domain.RecordCompeteInfo2;
import com.ruoyi.record.domain.RecordCompeteInfo3;
import com.ruoyi.record.mapper.RecordCompeteMapper;
import com.ruoyi.record.service.IRecordCompeteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 职称申报Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-09
 */
@Service
public class RecordCompeteServiceImpl extends ServiceImpl<RecordCompeteMapper, RecordCompete> implements IRecordCompeteService
{
    @Autowired
    private BasicUserMapper basicUserMapper;

    @Autowired
    private BasicPostMapper basicPostMapper;

    /**
     * 查询职称申报
     * 
     * @param competeId 职称申报主键
     * @return 职称申报
     */
    @Override
    public RecordCompete selectRecordCompeteByCompeteId(Long competeId)
    {
        return baseMapper.selectRecordCompeteByCompeteId(competeId);
    }

    /**
     * 查询职称申报列表
     * 
     * @param recordCompete 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordCompete> selectRecordCompeteList(RecordCompete recordCompete)
    {
        return baseMapper.selectRecordCompeteList(recordCompete);
    }

    /**
     * 新增职称申报
     * 
     * @param recordCompete 职称申报
     * @return 结果
     */
    @Override
    public int insertRecordCompete(RecordCompete recordCompete)
    {
        recordCompete.setCreateTime(DateUtils.getNowDate());
        int rows = baseMapper.insert(recordCompete);
        insertRecordCompeteInfo(recordCompete);
        return rows;
    }

    /**
     * 修改职称申报
     * 
     * @param recordCompete 职称申报
     * @return 结果
     */
    @Override
    public int updateRecordCompete(RecordCompete recordCompete)
    {
        recordCompete.setUpdateTime(DateUtils.getNowDate());
        baseMapper.deleteRecordCompeteInfo1ByCompeteId(recordCompete.getCompeteId());
        baseMapper.deleteRecordCompeteInfo2ByCompeteId(recordCompete.getCompeteId());
        baseMapper.deleteRecordCompeteInfo3ByCompeteId(recordCompete.getCompeteId());
        insertRecordCompeteInfo(recordCompete);
        return baseMapper.updateById(recordCompete);
    }

    /**
     * 批量删除职称申报
     * 
     * @param competeIds 需要删除的职称申报主键
     * @return 结果
     */
    @Override
    public int deleteRecordCompeteByCompeteIds(String competeIds)
    {
        baseMapper.deleteRecordCompeteInfo1ByCompeteIds(Convert.toLongArray(competeIds));
        baseMapper.deleteRecordCompeteInfo2ByCompeteIds(Convert.toLongArray(competeIds));
        baseMapper.deleteRecordCompeteInfo3ByCompeteIds(Convert.toLongArray(competeIds));
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(competeIds)));
    }

    /**
     * 删除职称申报信息
     * 
     * @param competeId 职称申报主键
     * @return 结果
     */
    @Override
    public int deleteRecordCompeteByCompeteId(Long competeId)
    {
        baseMapper.deleteRecordCompeteInfo1ByCompeteId(competeId);
        baseMapper.deleteRecordCompeteInfo2ByCompeteId(competeId);
        baseMapper.deleteRecordCompeteInfo3ByCompeteId(competeId);
        return baseMapper.deleteById(competeId);
    }

    /**
     * 查询职称申报列表
     *
     * @param recordCompete 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordCompete> selectVerifyCompeteList(RecordCompete recordCompete)
    {
        return baseMapper.selectVerifyCompeteList(recordCompete);
    }

    /**
     * 查询职称申报列表
     *
     * @param recordCompete 职称申报
     * @return 职称申报
     */
    @Override
    public List<RecordCompete> selectScoreCompeteList(RecordCompete recordCompete)
    {
        return baseMapper.selectScoreCompeteList(recordCompete);
    }

    /**
     * 职称申报审批
     * @param recordCompete
     * @return
     */
    @Override
    public int verifyRecordCompete(RecordCompete recordCompete)
    {
        LambdaUpdateWrapper<RecordCompete> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(RecordCompete::getVerifyFlag, recordCompete.getVerifyFlag());
        updateWrapper.eq(RecordCompete::getCompeteId, recordCompete.getCompeteId());
        return baseMapper.update(null, updateWrapper);
    }

    /**
     * 职称申报审批
     * @param recordCompete
     * @return
     */
    @Override
    public int scoreRecordCompete(RecordCompete recordCompete)
    {
        LambdaUpdateWrapper<RecordCompete> updateWrapper = Wrappers.lambdaUpdate();
        if(StringUtils.isNotEmpty(recordCompete.getScore1())) {
            updateWrapper.set(RecordCompete::getScore1, recordCompete.getScore1());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore2())) {
            updateWrapper.set(RecordCompete::getScore2, recordCompete.getScore2());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore3())) {
            updateWrapper.set(RecordCompete::getScore3, recordCompete.getScore3());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore4())) {
            updateWrapper.set(RecordCompete::getScore4, recordCompete.getScore4());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore5())) {
            updateWrapper.set(RecordCompete::getScore5, recordCompete.getScore5());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore6())) {
            updateWrapper.set(RecordCompete::getScore6, recordCompete.getScore6());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore7())) {
            updateWrapper.set(RecordCompete::getScore7, recordCompete.getScore7());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore8())) {
            updateWrapper.set(RecordCompete::getScore8, recordCompete.getScore8());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore9())) {
            updateWrapper.set(RecordCompete::getScore9, recordCompete.getScore9());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore10())) {
            updateWrapper.set(RecordCompete::getScore10, recordCompete.getScore10());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore11())) {
            updateWrapper.set(RecordCompete::getScore11, recordCompete.getScore11());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore12())) {
            updateWrapper.set(RecordCompete::getScore12, recordCompete.getScore12());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore13())) {
            updateWrapper.set(RecordCompete::getScore13, recordCompete.getScore13());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore14())) {
            updateWrapper.set(RecordCompete::getScore14, recordCompete.getScore14());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore15())) {
            updateWrapper.set(RecordCompete::getScore15, recordCompete.getScore15());
        }
        if(StringUtils.isNotEmpty(recordCompete.getScore16())) {
            updateWrapper.set(RecordCompete::getScore16, recordCompete.getScore16());
        }
        updateWrapper.eq(RecordCompete::getCompeteId, recordCompete.getCompeteId());
        return baseMapper.update(null, updateWrapper);
    }

    /**
     * 导入档案工资
     *
     * @param competeList 档案工资列表
     * @return 结果
     */
    @Override
    public String importRecordCompete(List<RecordCompete> competeList, boolean isUpdateSupport)
    {
        if (StringUtils.isNull(competeList) || competeList.size() == 0)
        {
            throw new ServiceException("导入职称申报数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecordCompete recordCompete : competeList)
        {
            try
            {
                if(StringUtils.isEmpty(recordCompete.getIdCard())){
                    continue;
                }
                //验证用户是否存在
                BasicUser basicUser = basicUserMapper.selectOne(new LambdaQueryWrapper<BasicUser>().eq(BasicUser::getIdCard, recordCompete.getIdCard()));
                if(StringUtils.isNull(basicUser)) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + recordCompete.getUserName() + " 不存在");
                    continue;
                }

                BasicPost basicPost = basicPostMapper.selectOne(new LambdaQueryWrapper<BasicPost>().eq(BasicPost::getUserId, basicUser.getId()).eq(BasicPost::getIsDefault, "Y"));
                if(StringUtils.isNotNull(basicPost)) {
                    recordCompete.setPostName(basicPost.getPostName());
                    recordCompete.setObtainLevel(basicPost.getObtainLevel());
                    recordCompete.setObtainTime(basicPost.getObtainTime());
                    recordCompete.setPostLevel(basicPost.getPostLevel());
                    recordCompete.setEngageTime(basicPost.getEngageTime());
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(StringUtils.isNotEmpty(recordCompete.getVerifyTime()) && recordCompete.getVerifyTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date verifyTime = dateFormat.parse(recordCompete.getVerifyTime());
                    recordCompete.setVerifyTime(DateUtils.parseDateToStr("yyyy-MM-dd", verifyTime));
                }

                RecordCompete info = baseMapper.selectOne(new LambdaQueryWrapper<RecordCompete>()
                        .eq(RecordCompete::getCreateBy, recordCompete.getIdCard())
                        .eq(RecordCompete::getCompeteLevel, recordCompete.getCompeteLevel()));
                if(StringUtils.isNull(info)) {
                    recordCompete.setVerifyFlag("1");
                    recordCompete.setCreateBy(basicUser.getIdCard());
                    this.insertRecordCompete(recordCompete);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行职称竞聘信息导入成功");
                }
                else if (isUpdateSupport)
                {
                    recordCompete.setCompeteId(info.getCompeteId());
                    recordCompete.setVerifyFlag("1");
                    recordCompete.setUpdateBy(basicUser.getIdCard());
                    this.updateRecordCompete(recordCompete);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行职称竞聘信息更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行职称竞聘信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行职称竞聘信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 新增申请内容信息
     *
     * @param recordCompete 申请记录对象
     */
    public void insertRecordCompeteInfo(RecordCompete recordCompete)
    {
        List<RecordCompeteInfo1> competeInfo1List = recordCompete.getInfo1List();
        if (StringUtils.isNotNull(competeInfo1List))
        {
            List<RecordCompeteInfo1> info1List = new ArrayList<RecordCompeteInfo1>();
            for (RecordCompeteInfo1 competeInfo1 : competeInfo1List)
            {
                competeInfo1.setCompeteId(recordCompete.getCompeteId());
                info1List.add(competeInfo1);
            }
            if (info1List.size() > 0)
            {
                baseMapper.batchRecordCompeteInfo1(info1List);
            }
        }
        List<RecordCompeteInfo2> competeInfo2List = recordCompete.getInfo2List();
        if (StringUtils.isNotNull(competeInfo2List))
        {
            List<RecordCompeteInfo2> info2List = new ArrayList<RecordCompeteInfo2>();
            for (RecordCompeteInfo2 competeInfo2 : competeInfo2List)
            {
                competeInfo2.setCompeteId(recordCompete.getCompeteId());
                info2List.add(competeInfo2);
            }
            if (info2List.size() > 0)
            {
                baseMapper.batchRecordCompeteInfo2(info2List);
            }
        }
        List<RecordCompeteInfo3> competeInfo3s = recordCompete.getInfo3List();
        if (StringUtils.isNotNull(competeInfo3s))
        {
            List<RecordCompeteInfo3> info3List = new ArrayList<RecordCompeteInfo3>();
            for (RecordCompeteInfo3 competeInfo3 : competeInfo3s)
            {
                competeInfo3.setCompeteId(recordCompete.getCompeteId());
                info3List.add(competeInfo3);
            }
            if (info3List.size() > 0)
            {
                baseMapper.batchRecordCompeteInfo3(info3List);
            }
        }
    }
}
